package com.xuxingcan.findmyvoice.Util;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.GetDataCallback;
import com.avos.avoscloud.GetFileCallback;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.UpdatePasswordCallback;
import com.xuxingcan.findmyvoice.Activity.FeedbackActivity;
import com.xuxingcan.findmyvoice.Activity.SignUpActivity;
import com.xuxingcan.findmyvoice.Model.FeedbackModel;
import com.xuxingcan.findmyvoice.Model.ReceiveMessageModel;
import com.xuxingcan.findmyvoice.Model.SendMessageModel;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by xuxingcan on 16-3-30.
 */
public class LeanCloudUtil {
    public static final String FEED_BACK_CLASS = "XXC_FEED_BACK_CLASS";
    public static final String MESSAGE_CLASS = "XXC_MESSAGE_CLASS";
    public static final String MESSAGE_QUEUE_CLASS = "XXC_MESSAGE_QUEUE_CLASS";
    public static final String KEY_MESSAGE = "MESSAGE";
    public static final String KEY_USER = "USER";
    public static final String KEY_CONTENT = "CONTENT";
    public static final String KEY_PIC_FILE = "PIC_FILE_";
    //    public static final String KEY_PIC_URL = "PIC_URL_";
    public static final String KEY_AUDIO_FILE = "AUDIO_FILE";
    //    public static final String KEY_AUDIO_URL = "AUDIO_URL";
    public static final String KEY_AUDIO_DURATION = "AUDIO_DURATION";
    public static final String KEY_HEAD = "HEAD";
    public static final String KEY_USER_ICON = "USER_ICON";
    public static final String KEY_FEED_BACK_TITLE = "FEED_BACK_TITLE";
    public static final String KEY_FEED_BACK_CONTENT = "FEED_BACK_CONTENT";
    private static final String TAG = "LeanCloudUtil";


    public static void sendMsg(Activity activity, final SendMessageModel model, final sendMsgCallBack callBack) {
        final Handler mHandler = new Handler();
        final AVUser currentUser = AVUser.getCurrentUser();
        if (currentUser == null) {
            activity.startActivity(new Intent(activity, SignUpActivity.class));
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!new File(model.getAudioFile()).exists()) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.onError(new Exception("NoAudioFile"));
                            }
                        }
                    });
                    return;
                }
                try {
                    AVObject msg = new AVObject(MESSAGE_CLASS);
                    msg.put(KEY_USER, currentUser);
                    msg.put(KEY_HEAD, model.getHead());
                    msg.put(KEY_CONTENT, model.getContent());
                    for (int i = 0; i < model.getBitmaps().size(); i++) {
                        AVFile file = new AVFile("file_pic_" + System.currentTimeMillis(), Bitmap2Bytes(model.getBitmaps().get(i)));
//                        file.save();
                        msg.put(KEY_PIC_FILE + i, file);
//                        msg.put(KEY_PIC_URL,file.getUrl());
                    }
                    AVFile file = AVFile.withAbsoluteLocalPath(KEY_AUDIO_FILE, model.getAudioFile());
                    file.addMetaData(KEY_AUDIO_DURATION, model.getAudioTime());
//                    file.save();
                    msg.put(KEY_AUDIO_FILE, file);
//                    msg.save();
                    AVObject avObject = new AVObject(MESSAGE_QUEUE_CLASS);
                    avObject.put(KEY_USER, currentUser);
                    avObject.put(KEY_MESSAGE, msg);
                    avObject.save();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.onSuccess();
                            }
                        }
                    });
                } catch (final Exception e) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.onError(e);
                            }
                        }
                    });
                }
            }
        }).start();
        return;
    }

    public interface sendMsgCallBack {
        void onError(Exception e);

        void onSuccess();
    }

    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
        return baos.toByteArray();
    }

    public interface getMsgCallBack {
        void onError(Exception e);

        void onSuccess(ArrayList<ReceiveMessageModel> messageModels);
    }

    public static void getMessageQueue(final int skip, final int max, final Date mDate, final boolean isBigger, final getMsgCallBack callBack) {
        final Handler mHandler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final ArrayList<ReceiveMessageModel> messageModels = new ArrayList<>();
                    AVQuery<AVObject> query = new AVQuery<>(MESSAGE_QUEUE_CLASS);
                    query.setSkip(skip);
                    query.setLimit(max);
                    if (mDate != null) {
                        if (isBigger) {
                            query.whereGreaterThan("createdAt", mDate);
                        } else {
                            query.whereLessThan("createdAt", mDate);
                        }
                    }
                    List<AVObject> list = query.find();
                    for (AVObject o : list) {
                        AVObject msg = getAvObjectByObjectId(MESSAGE_CLASS, o.getAVObject(KEY_MESSAGE).getObjectId());
                        ReceiveMessageModel model = new ReceiveMessageModel();
                        model.setId(msg.getObjectId());
                        model.setContent(msg.getString(KEY_CONTENT));
                        model.setHead(msg.getString(KEY_HEAD));
                        ArrayList<String> bitmapUrls = new ArrayList<String>();
                        for (int i = 0; i < 3; i++) {
                            if (msg.getAVFile(KEY_PIC_FILE + i) != null)
                                bitmapUrls.add(msg.getAVFile(KEY_PIC_FILE + i).getUrl());
                        }
                        model.setBitmapUrls(bitmapUrls);
                        model.setAudioFileUrl(msg.getAVFile(KEY_AUDIO_FILE).getUrl());
                        model.setAudioFileId(msg.getAVFile(KEY_AUDIO_FILE).getObjectId());
                        model.setAudioTime((int) msg.getAVFile(KEY_AUDIO_FILE).getMetaData(KEY_AUDIO_DURATION));
                        model.setCreateDate(msg.getCreatedAt());
                        messageModels.add(model);
                    }
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.onSuccess(messageModels);
                            }
                        }
                    });
                } catch (final AVException e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null) {
                                callBack.onError(e);
                            }
                        }
                    });
                }
            }
        }).start();
    }

//    public static AVObject getMessage(final String id) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                AVObject msg = getAvObjectByObjectId(MESSAGE_CLASS, id);
//            }
//        }).start();
//    }

    public static AVObject getAvObjectByObjectId(String whichClass, String ID) {
        try {
            AVQuery<AVObject> query = new AVQuery<AVObject>(whichClass);
            query.whereEqualTo("objectId", ID);
            return query.find().get(0);
        } catch (AVException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void getAudioFile(String id, final GetDataCallback callback) {
        AVFile.withObjectIdInBackground(id, new GetFileCallback<AVFile>() {
            @Override
            public void done(AVFile avFile, AVException e) {
                if (e == null) {
                    avFile.getDataInBackground(callback);
                } else {
                    callback.done(null, e);
                }
            }
        });
    }

    public static void clearAudioFileCacheIfNecessary(File dir) {
        TreeMap<Long, File> tm = new TreeMap<>();
        if (dir.exists() && dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files.length > 40) {
                for (int i = 0; i < files.length; i++) {
                    tm.put(files[i].lastModified(), files[i]);
                }
                ArrayList<File> fileArrayList = new ArrayList<>();
                Set<Long> set = tm.keySet();
                Iterator<Long> it = set.iterator();
                while (it.hasNext()) {
                    Object key = it.next();
                    Object objValue = tm.get(key);
                    fileArrayList.add((File) objValue);
                }
                int deleteNum = fileArrayList.size() - 20;
                for (int i = 0; i < deleteNum; i++) {
                    fileArrayList.remove(0).delete();
                }
            }
        }
    }

    public static void getFilePathName(File dir) {
        TreeMap<Long, File> tm = new TreeMap<Long, File>();
        File subFile[] = dir.listFiles();
        int fileNum = subFile.length;
        for (int i = 0; i < fileNum; i++) {
            tm.put(subFile[i].lastModified(), subFile[i]);
        }
        Log.d(TAG, "按时间从前到后排序--->");
        Log.d(TAG, "最早的一个文件的路径-->" + tm.get(tm.firstKey()).getPath() + tm.firstKey());
        Log.d(TAG, "最近的一个文件的路径-->" + tm.get(tm.lastKey()).getPath() + tm.lastKey());
        Set<Long> set = tm.keySet();
        Iterator<Long> it = set.iterator();
        while (it.hasNext()) {
            Object key = it.next();
            Object objValue = tm.get(key);
            File tempFile = (File) objValue;
            Date date = new Date((Long) key);
            Log.d(TAG, tempFile.getPath() + "\t" + date);
        }
    }

    public interface updatePasswordCallback {
        void onSuccess();

        void onFail(Exception e);
    }

    public static void updatePassword(final String originPassword, final String newPassword, final updatePasswordCallback callback) {
        final Handler mHandler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    AVUser userA = AVUser.logIn(AVUser.getCurrentUser().getUsername(), originPassword);
                    userA.updatePasswordInBackground(originPassword, newPassword, new UpdatePasswordCallback() {
                        @Override
                        public void done(final AVException e) {
                            if (e == null) {
                                if (callback != null) {
                                    callback.onSuccess();
                                }
                            } else {
                                if (callback != null) {
                                    callback.onFail(e);
                                }
                            }
                        }
                    });
                } catch (final AVException e) {
                    e.printStackTrace();
                    if (callback != null) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onFail(e);
                            }
                        });
                    }
                }
            }
        }).start();

    }

    public static void sendFeedBack(FeedbackModel model, final sendMsgCallBack callBack) {
        AVObject msg = new AVObject(FEED_BACK_CLASS);
        msg.put(KEY_FEED_BACK_TITLE, model.getTitle());
        msg.put(KEY_FEED_BACK_CONTENT, model.getContent());
        msg.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e == null) {
                    if (callBack != null) {
                        callBack.onSuccess();
                    }
                } else {
                    if (callBack != null) {
                        callBack.onError(e);
                    }
                }
            }
        });
    }
}
